package com.weasel.helper;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * Created by Dylan on 2015/12/8.
 */
public final class TaskScheduledExecutor {

    private final static int DEFAULT_THREAD_COUNT = 1;
    private static int threadCount = DEFAULT_THREAD_COUNT;

    private ScheduledExecutorService service;

    {
        service = Executors.newScheduledThreadPool(threadCount, new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);
                return thread;
            }
        });
    }

    public static TaskScheduledExecutor scheduled(int _threadCount){
        if(_threadCount < 1){
            _threadCount = DEFAULT_THREAD_COUNT;
        }
        threadCount = _threadCount;
        return new TaskScheduledExecutor();
    }

    public static TaskScheduledExecutor scheduled(){
        return scheduled(DEFAULT_THREAD_COUNT);
    }

    /**执行任务
     * @param command  任务
     * @param intervalMinutes  立即开始，并intervalMinutes分钟执行一次
     */
    public void submitTask(Runnable command,long intervalMinutes){
        submitTask(command,intervalMinutes,TimeUnit.MINUTES);
    }

    /**执行任务
     * @param command 任务
     * @param initialDelay 立即开始,intervalMinutes时间间隔执行一次
     * @param unit  时间间隔单位
     */
    public void submitTask(Runnable command,long initialDelay,TimeUnit unit){
        submitTask(command, 0, initialDelay, unit);
    }

    /**执行任务
     * @param command 任务
     * @param initialDelay 开始执行时间
     * @param delay 执行时间间隔
     * @param unit  时间间隔单位
     */
    public void submitTask(Runnable command,long initialDelay,long delay,TimeUnit unit){
        service.scheduleWithFixedDelay(command, initialDelay, delay, unit);
    }

    public void shutdown(){
        service.shutdownNow();
    }

    public static void main(String [] args){
        TaskScheduledExecutor.scheduled()
                             .submitTask(new Runnable() {
                                 @Override
                                 public void run() {
                                    System.out.println("execute");
                                 }
                             },1,TimeUnit.SECONDS);
        KeepAliveHelper.keepAlive();
    }
}
